package com.ruoyi.web.controller.tool.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayFundAuthOrderFreezeResponse;
import com.alipay.api.response.AlipayFundCouponOrderAgreementPayResponse;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.ruoyi.framework.aspectj.DataScopeAspect;
import com.ruoyi.web.core.utils.AjaxResult;
import com.ruoyi.web.core.utils.AliPayBean;
import com.ruoyi.web.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequestMapping({"/aliPay"})
@Controller
/* loaded from: AliPayController.class */ public class AliPayController extends AbstractAliPayApiController {
    private static final Logger     log        = LoggerFactory.getLogger(AliPayController.class);
    private static final String     NOTIFY_URL = "/aliPay/cert_notify_url";
    private static final String     RETURN_URL = "/aliPay/cert_return_url";
    private final        AjaxResult result     = new AjaxResult();
    @Resource
    private              AliPayBean aliPayBean;

    @Override // com.ruoyi.web.controller.tool.alipay.AbstractAliPayApiController
    public AliPayApiConfig getApiConfig() throws AlipayApiException {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(this.aliPayBean.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder().setAppId(this.aliPayBean.getAppId()).setAliPayPublicKey(this.aliPayBean.getPublicKey()).setAppCertPath(this.aliPayBean.getAppCertPath()).setAliPayCertPath(this.aliPayBean.getAliPayCertPath()).setAliPayRootCertPath(this.aliPayBean.getAliPayRootCertPath()).setCharset("UTF-8").setPrivateKey(this.aliPayBean.getPrivateKey()).setServiceUrl(this.aliPayBean.getServerUrl()).setSignType("RSA2").buildByCert();
        }
        return aliPayApiConfig;
    }

    @RequestMapping({""})
    @ResponseBody
    public String index() {
        return "欢迎使用 IJPay 中的支付宝支付 -By Javen  <br/><br>  交流群：723992875、864988890";
    }

    @RequestMapping({"/test"})
    @ResponseBody
    public AliPayApiConfig test() {
        AliPayApiConfig aliPayApiConfig = AliPayApiConfigKit.getAliPayApiConfig();
        log.info("charset>" + aliPayApiConfig.getCharset());
        return aliPayApiConfig;
    }

    @RequestMapping({"/appPay"})
    @ResponseBody
    public AjaxResult appPay() {
        try {
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("我是测试数据-By Javen");
            model.setSubject("App支付测试-By Javen");
            model.setOutTradeNo(StringUtils.getOutTradeNo());
            model.setTimeoutExpress("30m");
            model.setTotalAmount("0.01");
            model.setPassbackParams("callback params");
            model.setProductCode("QUICK_MSECURITY_PAY");
            this.result.success(AliPayApi.appPayToResponse(model, this.aliPayBean.getDomain() + NOTIFY_URL).getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            this.result.addError("system error:" + e.getMessage());
        }
        return this.result;
    }

    @RequestMapping({"/wapPay"})
    @ResponseBody
    public void wapPay(HttpServletResponse response) {
        String                 returnUrl = this.aliPayBean.getDomain() + RETURN_URL;
        String                 notifyUrl = this.aliPayBean.getDomain() + NOTIFY_URL;
        AlipayTradeWapPayModel model     = new AlipayTradeWapPayModel();
        model.setBody("我是测试数据-By Javen");
        model.setSubject("Javen Wap支付测试");
        model.setTotalAmount("1");
        model.setPassbackParams("1");
        String outTradeNo = StringUtils.getOutTradeNo();
        System.out.println("wap outTradeNo>" + outTradeNo);
        model.setOutTradeNo(outTradeNo);
        model.setProductCode("QUICK_WAP_PAY");
        try {
            AliPayApi.wapPay(response, model, returnUrl, notifyUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping({"/pcPay"})
    @ResponseBody
    public void pcPay(HttpServletResponse response) {
        try {
            String outTradeNo = StringUtils.getOutTradeNo();
            log.info("pc outTradeNo>" + outTradeNo);
            String                  notifyUrl = this.aliPayBean.getDomain() + NOTIFY_URL;
            AlipayTradePagePayModel model     = new AlipayTradePagePayModel();
            model.setOutTradeNo(outTradeNo);
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTotalAmount("88.88");
            model.setSubject("Javen PC支付测试");
            model.setBody("Javen IJPay PC支付测试");
            model.setPassbackParams("passback_params");
            AliPayApi.tradePage(response, model, notifyUrl, this.aliPayBean.getDomain() + RETURN_URL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping({"/tradePay"})
    @ResponseBody
    public String tradePay(@RequestParam("authCode") String authCode, @RequestParam("scene") String scene) {
        String subject = null;
        if (scene.equals("wave_code")) {
            subject = "Javen 支付宝声波支付测试";
        }
        else if (scene.equals("bar_code")) {
            subject = "Javen 支付宝条形码支付测试";
        }
        String              notifyUrl = this.aliPayBean.getDomain() + NOTIFY_URL;
        AlipayTradePayModel model     = new AlipayTradePayModel();
        model.setAuthCode(authCode);
        model.setSubject(subject);
        model.setTotalAmount("100");
        model.setOutTradeNo(StringUtils.getOutTradeNo());
        model.setScene(scene);
        try {
            return AliPayApi.tradePayToResponse(model, notifyUrl).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradePreCreatePay"})
    @ResponseBody
    public String tradePreCreatePay() {
        String                    notifyUrl = this.aliPayBean.getDomain() + NOTIFY_URL;
        AlipayTradePrecreateModel model     = new AlipayTradePrecreateModel();
        model.setSubject("Javen 支付宝扫码支付测试");
        model.setTotalAmount("86");
        model.setStoreId("123");
        model.setTimeoutExpress("5m");
        model.setOutTradeNo(StringUtils.getOutTradeNo());
        try {
            return JSONObject.parseObject(AliPayApi.tradePrecreatePayToResponse(model, notifyUrl).getBody()).getJSONObject("alipay_trade_precreate_response").getString("qr_code");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/transfer"})
    @ResponseBody
    public String transfer() {
        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
        model.setOutBizNo(StringUtils.getOutTradeNo());
        model.setPayeeType("ALIPAY_LOGONID");
        model.setPayeeAccount("gxthqd7606@sandbox.com");
        model.setAmount("66");
        model.setPayerShowName("测试退款");
        model.setPayerRealName("沙箱环境");
        model.setRemark("javen测试单笔转账到支付宝");
        try {
            return AliPayApi.transferToResponse(model).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/transferQuery"})
    @ResponseBody
    public String transferQuery(@RequestParam(required = false, name = "outBizNo") String outBizNo, @RequestParam(required = false, name = "orderId") String orderId) {
        AlipayFundTransOrderQueryModel model = new AlipayFundTransOrderQueryModel();
        if (StringUtils.isNotEmpty(outBizNo)) {
            model.setOutBizNo(outBizNo);
        }
        if (StringUtils.isNotEmpty(orderId)) {
            model.setOrderId(orderId);
        }
        try {
            return AliPayApi.transferQueryToResponse(model).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/uniTransfer"})
    @ResponseBody
    public String uniTransfer() {
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
        model.setOutBizNo(StringUtils.getOutTradeNo());
        model.setTransAmount("1");
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");
        model.setBizScene("DIRECT_TRANSFER");
        model.setOrderTitle("统一转账-转账至支付宝账户");
        model.setRemark("IJPay 测试统一转账");
        Participant payeeInfo = new Participant();
        payeeInfo.setIdentity("gxthqd7606@sandbox.com");
        payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
        payeeInfo.setName("沙箱环境");
        model.setPayeeInfo(payeeInfo);
        try {
            return AliPayApi.uniTransferToResponse(model, null).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/uniTransferQuery"})
    @ResponseBody
    public String uniTransferQuery(@RequestParam(required = false, name = "outBizNo") String outBizNo, @RequestParam(required = false, name = "orderId") String orderId) {
        AlipayFundTransCommonQueryModel model = new AlipayFundTransCommonQueryModel();
        if (StringUtils.isNotEmpty(outBizNo)) {
            model.setOutBizNo(outBizNo);
        }
        if (StringUtils.isNotEmpty(orderId)) {
            model.setOrderId(orderId);
        }
        try {
            return AliPayApi.transCommonQueryToResponse(model, null).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/accountQuery"})
    @ResponseBody
    public String accountQuery(@RequestParam(required = true, name = "aliPayUserId") String aliPayUserId) {
        AlipayFundAccountQueryModel model = new AlipayFundAccountQueryModel();
        model.setAlipayUserId(aliPayUserId);
        model.setAccountType("ACCTRANS_ACCOUNT");
        try {
            return AliPayApi.accountQueryToResponse(model, null).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/authOrderFreeze"})
    @ResponseBody
    public AlipayFundAuthOrderFreezeResponse authOrderFreeze(@RequestParam("auth_code") String authCode) {
        try {
            AlipayFundAuthOrderFreezeModel model = new AlipayFundAuthOrderFreezeModel();
            model.setOutOrderNo(StringUtils.getOutTradeNo());
            model.setOutRequestNo(StringUtils.getOutTradeNo());
            model.setAuthCode(authCode);
            model.setAuthCodeType("bar_code");
            model.setOrderTitle("资金授权冻结-By IJPay");
            model.setAmount("36");
            model.setProductCode("PRE_AUTH");
            return AliPayApi.authOrderFreezeToResponse(model);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/agreementPay"})
    @ResponseBody
    public AlipayFundCouponOrderAgreementPayResponse agreementPay() {
        try {
            AlipayFundCouponOrderAgreementPayModel model = new AlipayFundCouponOrderAgreementPayModel();
            model.setOutOrderNo(StringUtils.getOutTradeNo());
            model.setOutRequestNo(StringUtils.getOutTradeNo());
            model.setOrderTitle("红包协议支付接口-By IJPay");
            model.setAmount("36");
            model.setPayerUserId("2088102180432465");
            return AliPayApi.fundCouponOrderAgreementPayToResponse(model);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/dataDataServiceBill"})
    @ResponseBody
    public String dataDataServiceBill(@RequestParam("billDate") String billDate) {
        try {
            AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
            model.setBillType("trade");
            model.setBillDate(billDate);
            return AliPayApi.billDownloadUrlQuery(model);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradeRefund"})
    @ResponseBody
    public String tradeRefund(@RequestParam(required = false, name = "outTradeNo") String outTradeNo, @RequestParam(required = false, name = "tradeNo") String tradeNo) {
        try {
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            if (StringUtils.isNotEmpty(outTradeNo)) {
                model.setOutTradeNo(outTradeNo);
            }
            if (StringUtils.isNotEmpty(tradeNo)) {
                model.setTradeNo(tradeNo);
            }
            model.setRefundAmount("86.00");
            model.setRefundReason("正常退款");
            return AliPayApi.tradeRefundToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradeQuery"})
    @ResponseBody
    public String tradeQuery(@RequestParam(required = false, name = "outTradeNo") String outTradeNo, @RequestParam(required = false, name = "tradeNo") String tradeNo) {
        try {
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            if (StringUtils.isNotEmpty(outTradeNo)) {
                model.setOutTradeNo(outTradeNo);
            }
            if (StringUtils.isNotEmpty(tradeNo)) {
                model.setTradeNo(tradeNo);
            }
            return AliPayApi.tradeQueryToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradeQueryByStr"})
    @ResponseBody
    public String tradeQueryByStr(@RequestParam(required = false, name = "outTradeNo") String outTradeNo, @RequestParam(required = false, name = "tradeNo") String tradeNo) {
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        if (StringUtils.isNotEmpty(outTradeNo)) {
            model.setOutTradeNo(outTradeNo);
        }
        if (StringUtils.isNotEmpty(tradeNo)) {
            model.setTradeNo(tradeNo);
        }
        try {
            return AliPayApi.tradeQueryToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradeCreate"})
    @ResponseBody
    public String tradeCreate(@RequestParam("outTradeNo") String outTradeNo) {
        String                 notifyUrl = this.aliPayBean.getDomain() + NOTIFY_URL;
        AlipayTradeCreateModel model     = new AlipayTradeCreateModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount("88.88");
        model.setBody("Body");
        model.setSubject("Javen 测试统一收单交易创建接口");
        model.setBuyerLogonId("abpkvd0206@sandbox.com");
        try {
            return AliPayApi.tradeCreateToResponse(model, notifyUrl).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradeCancel"})
    @ResponseBody
    public String tradeCancel(@RequestParam(required = false, name = "outTradeNo") String outTradeNo, @RequestParam(required = false, name = "tradeNo") String tradeNo) {
        try {
            AlipayTradeCancelModel model = new AlipayTradeCancelModel();
            if (StringUtils.isNotEmpty(outTradeNo)) {
                model.setOutTradeNo(outTradeNo);
            }
            if (StringUtils.isNotEmpty(tradeNo)) {
                model.setTradeNo(tradeNo);
            }
            return AliPayApi.tradeCancelToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradeClose"})
    @ResponseBody
    public String tradeClose(@RequestParam("outTradeNo") String outTradeNo, @RequestParam("tradeNo") String tradeNo) {
        try {
            AlipayTradeCloseModel model = new AlipayTradeCloseModel();
            if (StringUtils.isNotEmpty(outTradeNo)) {
                model.setOutTradeNo(outTradeNo);
            }
            if (StringUtils.isNotEmpty(tradeNo)) {
                model.setTradeNo(tradeNo);
            }
            return AliPayApi.tradeCloseToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/tradeOrderSettle"})
    @ResponseBody
    public String tradeOrderSettle(@RequestParam("tradeNo") String tradeNo) {
        try {
            AlipayTradeOrderSettleModel model = new AlipayTradeOrderSettleModel();
            model.setOutRequestNo(StringUtils.getOutTradeNo());
            model.setTradeNo(tradeNo);
            return AliPayApi.tradeOrderSettleToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/toOauth"})
    @ResponseBody
    public void toOauth(HttpServletResponse response) {
        try {
            response.sendRedirect(AliPayApi.getOauth2Url(this.aliPayBean.getAppId(), this.aliPayBean.getDomain() + "/aliPay/redirect_uri"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping({"/redirect_uri"})
    @ResponseBody
    public String redirectUri(@RequestParam("app_id") String appId, @RequestParam("app_auth_code") String appAuthCode) {
        try {
            System.out.println("app_id:" + appId);
            System.out.println("app_auth_code:" + appAuthCode);
            AlipayOpenAuthTokenAppModel model = new AlipayOpenAuthTokenAppModel();
            model.setGrantType("authorization_code");
            model.setCode(appAuthCode);
            return AliPayApi.openAuthTokenAppToResponse(model).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/openAuthTokenAppQuery"})
    @ResponseBody
    public String openAuthTokenAppQuery(@RequestParam("appAuthToken") String appAuthToken) {
        try {
            AlipayOpenAuthTokenAppQueryModel model = new AlipayOpenAuthTokenAppQueryModel();
            model.setAppAuthToken(appAuthToken);
            return AliPayApi.openAuthTokenAppQueryToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/batchTrans"})
    @ResponseBody
    public void batchTrans(HttpServletResponse response) {
        try {
            Map<String, String> params = new HashMap<>(15);
            params.put("partner", "PID");
            params.put("sign_type", "MD5");
            params.put("notify_url", this.aliPayBean.getDomain() + NOTIFY_URL);
            params.put("account_name", "xxx");
            params.put("detail_data", "流水号1^收款方账号1^收款账号姓名1^付款金额1^备注说明1|流水号2^收款方账号2^收款账号姓名2^付款金额2^备注说明2");
            params.put("batch_no", String.valueOf(System.currentTimeMillis()));
            params.put("batch_num", "1");
            params.put("batch_fee", "10.0");
            params.put("email", "xx@xxx.com");
            AliPayApi.batchTrans(params, this.aliPayBean.getPrivateKey(), "MD5", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping({"/voucherGenerate"})
    @ResponseBody
    public String voucherGenerate(@RequestParam("tradeNo") String tradeNo) {
        try {
            AlipayCommerceCityfacilitatorVoucherGenerateModel model = new AlipayCommerceCityfacilitatorVoucherGenerateModel();
            model.setCityCode("440300");
            model.setTradeNo(tradeNo);
            model.setTotalFee("8");
            model.setTicketNum("2");
            model.setTicketType("oneway");
            model.setSiteBegin("001");
            model.setSiteEnd("002");
            model.setTicketPrice(DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD);
            return AliPayApi.voucherGenerateToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping({"/return_url"})
    @ResponseBody
    public String returnUrl(HttpServletRequest request) {
        try {
            Map<String, String> map = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            if (AlipaySignature.rsaCheckV1(map, this.aliPayBean.getPublicKey(), "UTF-8", "RSA2")) {
                System.out.println("return_url 验证成功");
                return "success";
            }
            System.out.println("return_url 验证失败");
            return "failure";
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @RequestMapping({"/cert_return_url"})
    @ResponseBody
    public String certReturnUrl(HttpServletRequest request) {
        try {
            Map<String, String> map = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            if (AlipaySignature.rsaCertCheckV1(map, this.aliPayBean.getAliPayCertPath(), "UTF-8", "RSA2")) {
                System.out.println("certReturnUrl 验证成功");
                return "success";
            }
            System.out.println("certReturnUrl 验证失败");
            return "failure";
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @RequestMapping({"/notify_url"})
    @ResponseBody
    public String notifyUrl(HttpServletRequest request) {
        try {
            Map<String, String> params = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            if (AlipaySignature.rsaCheckV1(params, this.aliPayBean.getPublicKey(), "UTF-8", "RSA2")) {
                System.out.println("notify_url 验证成功succcess");
                return "success";
            }
            System.out.println("notify_url 验证失败");
            return "failure";
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @RequestMapping({"/cert_notify_url"})
    @ResponseBody
    public String certNotifyUrl(HttpServletRequest request) {
        try {
            Map<String, String> params = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
            if (AlipaySignature.rsaCertCheckV1(params, this.aliPayBean.getAliPayCertPath(), "UTF-8", "RSA2")) {
                System.out.println("certNotifyUrl 验证成功succcess");
                return "success";
            }
            System.out.println("certNotifyUrl 验证失败");
            return "failure";
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }
}
